/**
 * Created by Tuffy on 16/1/18.
 */
'use strict';

(function() {
    //---------------------------------------------------
    // 日期格式化
    // 格式 YYYY/yyyy/YY/yy 表示年份
    // MM/M 月份
    // W/w 星期
    // dd/DD/d/D 日期
    // hh/HH/h/H 时间
    // mm/m 分钟
    // ss/SS/s/S 秒
    //---------------------------------------------------
    Date.prototype.Format = function(formatStr){
        var str = formatStr;
        var Week = ['日','一','二','三','四','五','六'];

        str=str.replace(/yyyy|YYYY/,this.getFullYear());
        str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));
        // 月份在JS里面是从0开始的
        str=str.replace(/MM/,this.getMonth()>=9?(this.getMonth()+1).toString():'0' + (this.getMonth()+1));
        str=str.replace(/M/g,this.getMonth());

        str=str.replace(/w|W/g,Week[this.getDay()]);

        str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
        str=str.replace(/d|D/g,this.getDate());

        str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());
        str=str.replace(/h|H/g,this.getHours());
        str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());
        str=str.replace(/m/g,this.getMinutes());

        str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());
        str=str.replace(/s|S/g,this.getSeconds());

        return str;
    };
})();

// 登陆使用
var Login = {

    /**
     * 获取本地用户信息
     */
    getLoginInfo: function() {
        return Lockr.get('username_localStorage');
    },

    /**
     * 设置本地用户信息
     * @param loginInfo 用户信息下对象
     */
    setLoginInfo: function(loginInfo) {
        Lockr.set('username_localStorage', loginInfo);
    },

    /**
     * 获取本地七牛上传token
     */
    getQiniUploadToken: function() {
        return Lockr.get('qiniuploadtoken_localStorage');
    },

    /**
     * 设置本地七牛上传token
     */
    setQiniUploadToken: function(qiniuploadtokenObj) {
        Lockr.set('qiniuploadtoken_localStorage', qiniuploadtokenObj);
    }
};

// 工具类
var Tools = {

    /**
     * 手机号是否合法
     * @param mobileNo 手机号码
     * @returns {boolean} 合法返回true，反之返回false
     */
    isMobileNo: function (mobileNo) {
        var reg = new RegExp('^1\\d{10}$');
        return reg.test(mobileNo);
    },
    /**
     * 将时间字符串, 转换为带时间符号时间字符串
     * @param timeStr 时间字符串
     * @returns {Date} 格式化之后时间字符串
     */
    timeStr2FormatTime: function(timeStr) {
        var rtnTimeStr = '';
        if (timeStr && timeStr.indexOf(':') < 0) {
            var timeArray = timeStr.split('');
            for (var i = 0; i < timeArray.length; i++) {
                rtnTimeStr += timeArray[i];
                if (i % 2 !== 0 && i + 1 < timeArray.length) {
                    rtnTimeStr += ':';
                }
            }
        }
        var date = new Date();
        var dateStr = date.Format('yyyy-MM-dd');
        var dateTimeStr = dateStr + ' ' + rtnTimeStr;
        var translateDate = dateTimeStr.replace("-", "/").replace("-", "/");
        var newDate = new Date(translateDate);
        return newDate;
    },
    /**
     * 获取某个日期加上几天之后的日期字符串，支持负数
     * @param dateParameter 某日起字符串
     * @param num 追加天数
     * @returns {String} 返回追加天数之后字符串
     */
    addByTransDate : function(dateParameter, num) {
        var translateDate = "", dateString = "", monthString = "", dayString = "";
        translateDate = dateParameter.replace("-", "/").replace("-", "/");
        var newDate = new Date(translateDate);
        newDate = newDate.valueOf();
        newDate = newDate + num * 24 * 60 * 60 * 1000;
        newDate = new Date(newDate);
        // 如果月份长度少于2，则前加 0 补位
        if ((newDate.getMonth() + 1).toString().length == 1) {
            monthString = 0 + "" + (newDate.getMonth() + 1).toString();
        } else {
            monthString = (newDate.getMonth() + 1).toString();
        }
        // 如果天数长度少于2，则前加 0 补位
        if (newDate.getDate().toString().length == 1) {
            dayString = 0 + "" + newDate.getDate().toString();
        } else {
            dayString = newDate.getDate().toString();
        }
        dateString = newDate.getFullYear() + "-" + monthString + "-"
            + dayString;
        return dateString;
    }
};

// 图片画廊对象
var ImageGallery = {
    callbackList: [], // 回调数组
    /**
     * 显示画廊
     * @param $rootScope 句柄
     * @param title modal 标题
     * @param items 项列表 [{
     *      src:'http://www.wired.com/images_blogs/660x440.jpg',
     *      sub: 'This is a <b>subtitle</b>'
     *  }]
     */
    uploadOkCallback: function(responseList) {
        var that = this;
        if (_.last(that._$rootScope.galleryItems).src === '') {
            that._$rootScope.galleryItems = _.initial(that._$rootScope.galleryItems);
        }
        angular.forEach(responseList, function(item) {
            var photoUrl = that._$rootScope.Settings.Context.qiniuDownload + item;
            if (that._$rootScope.photoNum === 1) {
                that._$rootScope.galleryItems = [{src: photoUrl, sub: ''}];
            } else {
                that._$rootScope.galleryItems.push({src: photoUrl, sub: ''});
            }
        });
        that.resetGalleryList();
    },
    show: function($rootScope, title, items, QiniuUploadToken, photoNum, onOkCallback) {
        this._$rootScope = $rootScope;
        this.QiniuUploadToken = QiniuUploadToken;
        this.onOkCallback = onOkCallback;
        $rootScope.galleryTitle = title;
        this.callbackList = items;
        angular.forEach(items, function(item) {
            item.src += '?imageView2/1/w/200';
        });
        items.push({src: ''});
        $rootScope.galleryItems = items;
        $rootScope.photoNum = photoNum;
        // 设置目前需上传张数
        this.photoNum = photoNum - $rootScope.galleryItems.length + 1;
        $rootScope.openGalleryModal();
    },
    /**
     * 选择删除图片
     */
    select: function() {
        this._$rootScope.gallerySelectFlag = true;
    },
    /**
     * 关闭modal
     * @param callback 回调函数
     */
    hide: function() {
        if (this.onOkCallback) {
            var copyData = [];
            angular.forEach(this.callbackList, function(item) {
                var src = "";
                if(typeof(item) == 'string'){
                    src = item;
                }else if(typeof(item) == 'object' && item.src.length>0){
                    src = item.src;
                }else{
                    return;
                }
                if(src.indexOf('?imageView2') > 0){
                    src = src.split('?')[0];
                }
                copyData.push(src)
            });
            this.onOkCallback(copyData);
            this.callbackList = [];
        }
    },
    /**
     * 重置画廊面板
     */
    resetGalleryList: function() {
        var that = this;
        that.callbackList = [];
        angular.forEach(this._$rootScope.galleryItems, function(item) {
            if (item.src.indexOf('?imageView2') > 0) {
                that.callbackList.push(item.src.split('?')[0]);
            } else if (item.src !== '') {
                that.callbackList.push(item.src);
                item.src += '?imageView2/1/w/200';
            }
        });
        if (_.last(this._$rootScope.galleryItems).src !== '') {
            this._$rootScope.galleryItems.push({src: ''});
        }
        that.photoNum = that._$rootScope.photoNum - that._$rootScope.galleryItems.length + 1;
    },

    // 上传照片
    uploadImage: function ($rootScope, $ionicLoading, $cordovaCamera, $cordovaImagePicker, $cordovaFileTransfer, Settings, index) {
        // 上传方法
        var that = this;
        // 返回数据列表
        var responseList = [];
        function uploadImage(filePath, itemLength) {
            $ionicLoading.show({
                template: '<ion-spinner icon="ios"></ion-spinner>'
            });
            $cordovaFileTransfer.upload(Settings.Context.qiniuUpload, filePath, {
                chunkedMode: false,
                mimeType: "image/jpg",
                params: {
                    token: that.QiniuUploadToken.getQiniuUploadToken()
                }
            })
            .then(function (result) {
                var responseObj = JSON.parse(result.response);
                responseList.push(responseObj.key);
                if (responseList.length === itemLength) {
                    that.uploadOkCallback(responseList);
                }
                // $rootScope.$broadcast(Settings.Context.qiniuUploadBroadcastKey, result.response);
            }, function (err) {
                console.log(JSON.stringify(err));
            }, function (progress) {
            }).finally(function() {
                $ionicLoading.hide();
            });
        };

        if (index === 1) { // 拍照
            var options = {
                destinationType: Camera.DestinationType.FILE_URI,
                sourceType: Camera.PictureSourceType.CAMERA,
            };
            $cordovaCamera.getPicture(options).then(function (imageURI) {
                uploadImage(imageURI, 1);
            }, function (err) {
                console.log(JSON.stringify(err));
            });
        } else if (index === 2) { // 相册
            var options = {
                maximumImagesCount: that.photoNum || 1,
                width: 800,
                height: 800,
                quality: 80
            };
            $cordovaImagePicker.getPictures(options).then(function (results) {
                angular.forEach(results, function(item) {
                    uploadImage(item, results.length);
                });
            }, function(error) {
                console.log(JSON.stringify(error));
            });
        }
    },
};